<?php


include_once './get_purl_key.php';
include_once './getUrlLocation.php';

// 函数：Base32编码
function base32Encode($str)
{
  $base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
  $bits = "";
  $base32 = "";
  for ($i = 0; $i < strlen($str); $i++) {
    $bit = decbin(ord($str[$i]));
    while (strlen($bit) < 8) {
      $bit = "0" . $bit;
    }
    $bits .= $bit;
  }

  while (strlen($bits) % 5 !== 0) {
    $bits .= "0";
  }
  for ($j = 0; $j < strlen($bits); $j += 5) {
    $chunk = substr($bits, $j, 5);
    $base32 .= $base32chars[bindec($chunk)];
  }
  while (strlen($base32) % 8 !== 0) {
    $base32 .= "=";
  }
  return str_replace("=", "HiFiNiYINYUECICHANG", $base32);
}

// 函数：生成参数
function generateParam($data, $key = '95wwwHiFiNicom27')
{
  $outText = '';
  for ($i = 0, $j = 0; $i < strlen($data); $i++, $j++) {
    if ($j == strlen($key)) {
      $j = 0;
    }
    $outText .= chr(ord($data[$i]) ^ ord($key[$j]));
  }
  return base32Encode($outText);
}

// 获取GET请求参数中的url
$url = isset($_GET['url']) ? $_GET['url'] : 'https://www.landui.com/';
// $url = isset($_GET['url']) ? $_GET['url'] : 'https://hifini.com/thread-34298.htm';

// 设置请求头
$headers = [
  'Cookie: tac_tmp=' . get_config(),
];
// 初始化cURL会话
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 禁用 SSL 证书验证（不推荐）

// 执行cURL会话并获取响应
$response = curl_exec($ch);
// 获取HTTP状态码
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// 初始化音乐信息变量
$musicUrl = [];
if ($response !== false) {

  // 获取 当前cookie中的tac_tmp并保存
  if (preg_match('/cookie.*?\'tac_tmp=\'.*?\'(.*?)\'.*?expires/is', $response, $matches)) {
    $tac_tmp = $matches[1];
    set_config($tac_tmp);
  }

  if (preg_match('/<h5>\s*?歌词\s*?<\/h5>(.*?)<h5>/is', $response, $matches)) {
    $lyrics = preg_replace('/<\/?p>\s*?/i', ' ', $matches[1]);
    $lyrics = trim(preg_replace('/\s+/', ' ', $lyrics));
    $lyricsArray = array_map('trim', explode(' ', $lyrics));
  } else {
    $lyricsArray = [];
  }

  if (preg_match('/title.*?\'(.*?)\',/i', $response, $matches)) {
    $name = $matches[1];
  } else {
    $name = '';
  }

  if (preg_match('/author.*?\'(.*?)\',/i', $response, $matches)) {
    $artist = $matches[1];
  } else {
    $artist = '';
  }

  if (preg_match('/pic.*?\'(.*?)\'/i', $response, $matches)) {
    $cover = $matches[1];
  } else {
    $cover = '';
  }

  /*
    if (preg_match('/url.*?\'(.*?)\',/gi', $response, $matches)) {
      $songUrl = $matches[1];
    } elseif (preg_match('/url.*?\'(.*?)\'.*?generateParam/i', $response, $matches)) {
      $songUrl = "https://hifini.com/" . $matches[1];
      if (preg_match('/generateParam\(\'(.*?)\'\),/i', $response, $paramMatches)) {
        $songUrl .= generateParam($paramMatches[1]);
      }
    } else {
      $songUrl = '';
    }
  */
  if (preg_match('/url.*?\'(.*?)helloworld\.mp3\',/', $response, $matches)) {
    if (preg_match('/formData.append\(\'play_key\'.*?\'(.*?)\'\)/i', $response, $play_key)) {
      $play_key = $play_key[1];
      $purl_key = purl_key($play_key);
    } else {
      $play_key = '';
      $purl_key = '{}';
    }

    $purl_key = json_decode($purl_key);

    $musicSourceUrl = $purl_key->purl_key1 ? getResponseHeaderLocation("https://hifini.com/get_music.php?key=" . $purl_key->purl_key1 . '&p=' . generateParam($purl_key->purl_key2)) : '';

  } elseif (preg_match('/url.*?\'(.*?)\'.*?generateParam/i', $response, $matches)) {
    $musicSourceUrl = "https://hifini.com/" . $matches[1];
    if (preg_match('/generateParam\(\'(.*?)\'\),/i', $response, $paramMatches)) {
      $musicSourceUrl .= generateParam($paramMatches[1]);
    }
  } elseif (preg_match('/url.*?\'(.*?)\',/i', $response, $matches)) {
    $musicSourceUrl = $matches[1];
  } else {
    $musicSourceUrl = '';
  }

  echo json_encode([
    'name' => $name,
    'artist' => $artist,
    'play_key' => $play_key,
    'url' => $musicSourceUrl,
    'cover' => $cover,
    'lyric' => $lyricsArray,
    'httpCode' => $httpCode,
    'purl_key1' => $purl_key->purl_key1,
    'purl_key2' => $purl_key->purl_key2,
    'verificationFail' => $purl_key->verificationFail,
    'tac_tmp' => $purl_key->tac_tmp,
  ]);

  // 如果或音乐播放地址，则记录播放次数+1
  if ($musicSourceUrl) {
    $filePath = 'call_music_count.txt';
    $call_music_count = get_config($filePath);
    set_config(++$call_music_count, $filePath);
  }

} else {
  echo $httpCode;
}
?>